﻿/*
 * @author: wizardc
 */

using System.Reflection;
using Dou.UI;
using DouEditor.Utils;
using UnityEditor;
using UnityEngine;

namespace DouEditor.UI
{
    [CustomEditor(typeof(UIDuplicator), true)]
    public class UIDuplicatorEditor : Editor
    {
        [MenuItem("GameObject/DouUI/Duplicator", false, 10)]
        private static void CreateUI(MenuCommand menuCommand)
        {
            var go = UIEditorUtil.CreateUIElement("Duplicator");
            go.AddComponent<UIDuplicator>();
            UIEditorUtil.PlaceUIElementRoot(go, menuCommand);
        }
        
        private UIDuplicator _target;
        
        private void OnEnable()
        {
            _target = (UIDuplicator) target;
        }

        public override void OnInspectorGUI()
        {
            _target.template = EditorGUILayout.ObjectField("模板", _target.template, typeof(GameObject), true) as GameObject;
            _target.container = EditorGUILayout.ObjectField("容器", _target.container, typeof(Transform), true) as Transform;
            var countChanged = EditorUtil.DrawNonPublicField(_target, "_count");
            var autoCloneChanged = EditorUtil.DrawNonPublicField(_target, "_autoClone");
            if (countChanged || autoCloneChanged)
            {
                if (_target.autoClone)
                {
                    _target.Clone();
                }
            }
            EditorGUI.BeginDisabledGroup(true);
            EditorGUILayout.PropertyField(serializedObject.FindProperty("_items"));
            EditorGUI.EndDisabledGroup();
        }
        
        [MenuItem("CONTEXT/UIDuplicator/清空克隆对象")]
        private static void CacheTargets(MenuCommand cmd)
        {
            var context = cmd.context as UIDuplicator;
            if (context == null)
            {
                return;
            }

            Undo.RecordObject(context, "ClearClone");
            EditorUtility.SetDirty(context);
            var invokeAttr = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.InvokeMethod;
            context.GetType().InvokeMember("ClearClone", invokeAttr, null, context, null);
        }
    }
}
